<template>
  <el-row class="up-row">
    <el-col :span="16" >
      <div class="firstfont">天津滨海机场航班管理系统</div>
    </el-col>
    <el-col :span="4" >
      <time>{{ timer }}</time>
    </el-col>
    <el-col :span="2">
      <img :src="userInfo.userimg" style="margin-top:30px;width:60px;height:60px; border-radius: 25px" />
    </el-col>
    <el-col :span="2">
      <!-- 下拉菜单 -->
      <el-dropdown>
              <span class="el-dropdown-link" style="line-height: 120px; color: black; border: 0px;font-size: 18px;">
              {{ userInfo.username }}
              </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item :icon="User" @click="rephotoBtn=true">修改头像</el-dropdown-item>
            <el-dropdown-item :icon="Setting" @click="repassBtn=true">修改密码</el-dropdown-item>
            <el-dropdown-item :icon="CircleClose" @click="cancleBtn">退出</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </el-col>
  </el-row>
  <el-dialog
      v-model="repassBtn"
      title="修改密码"
      width="500"
  >
    <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="auto"
    >
      <el-form-item prop="password" label="新密码">
        <el-input
            v-model="loginForm.password"
            placeholder="新密码"
            :prefix-icon="Lock"
            show-password
        />
      </el-form-item>
      <el-form-item prop="password2" label="再次输入">
        <el-input
            v-model="loginForm.password2"
            placeholder="请再次输入"
            :prefix-icon="Lock"
            show-password
        />
      </el-form-item>
      <el-form-item   style="margin-left: 40%">
        <el-button type="primary" @click="submitForm">确认</el-button>
        <el-button type="primary" @click="cancleFormBtn">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <el-dialog
      v-model="rephotoBtn"
      title="修改头像"
  >
    <el-upload
        class="avatar-uploader"
        action=""
        :http-request="path"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </el-dialog>
</template>

<script  setup>

import {ref, reactive,onMounted, onUnmounted} from 'vue'
import { useRouter } from "vue-router";
const router = useRouter() ;
import request from "@/utils/request";
// 导入外部js文件，并命名为 globaljs
import globaljs from '@/assets/js/global'
import {CircleClose, Lock, Setting, User} from "@element-plus/icons";
import {ElMessage} from "element-plus";
  // global.js 中 export导出未命名
const timer = ref(1)
const timerRef = ref()
const userInfo = reactive({
  'username' : 'a' ,
  'userimg' : require('@/assets/imgs/userphoto_default.jpg')
})
// 页面加载后，执行业务逻辑，onMounted中可以访问页面元素
onMounted(()=>{
  // 从SessionStorage取出数据
  let userstr = sessionStorage.getItem('username')
  //alert(userstr)//测试
  if(userstr == null || userstr == undefined || userstr == '') {
    router.push('/')
  } else {
    //读取用户名称
    userInfo.username = JSON.parse(userstr).sysuser.username
    if (null!=JSON.parse(userstr).sysuser.photourl){
      //读取用户图片
      userInfo.userimg = JSON.parse(userstr).sysuser.photourl
    }
  }
  // 更新 userInfo.username
  //////////////////////////////
  // 获取日期时间
  timerRef.value = setInterval(()=>{
    timer.value = globaljs.current()
  } , 1000)
})
// 页面停止加载（页面元素销毁，此函数中不能访问页面元素）
onUnmounted(()=>{
  clearInterval(timerRef)
})
//修改头像
const rephotoBtn=ref(false)
const imageUrl=ref('')

const handleAvatarSuccess=(response,uploadFile)=> {
 imageUrl.value = URL.createObjectURL(uploadFile.raw)
   if (200 == response.data.errorCode){
     userInfo.value.userimg =response.data.data
   }
}
 const path=(param)=>{
   // 从SessionStorage取出数据
   let userstr = sessionStorage.getItem('username')
   const PhotoIDData = {
     id: JSON.parse(userstr).sysuser.id,
     userphoto:param.file
   }
   request({
     url:'/file/rephoto/'+PhotoIDData.id,
     method:'post',
     data:PhotoIDData,
     headers: {
       'Content-Type': 'multipart/form-data'
     }
   }).then(req=>{
     if(200==req.data.errorCode){
       ElMessage({
         type:"success",
         message:'修改成功！'
       })
       userInfo.userimg =req.data.data
       rephotoBtn.value=false
     }else {
       ElMessage({
         type:"error",
         message:'修改失败！'
       })
     }

   })
}
const beforeAvatarUpload= (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('请上传JPG格式的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}
const repassBtn=ref(false)
//修改密码确认按钮
const submitForm=()=> {
  if (loginForm.password!=loginForm.password2){
    ElMessage({
      type: 'error',
      message: '两次填写密码不一致！'
    })
  }else {
  // 从SessionStorage取出数据
  let userstr = sessionStorage.getItem('username')
  const token = JSON.parse(userstr).token
  const formIDData = {
    id: JSON.parse(userstr).sysuser.id,
    password:loginForm.password
  }
  const formgetID = reactive({...formIDData})
  request({
    url: '/sys/user/updatepass',
    method: 'put',
    data: formgetID,
    headers: {
      'token': token,
      'content-type':"application/json;charset:UTF-8"
    }
  }).then(req => {
    if (200==req.data.errorCode){
      ElMessage({
        type: 'success',
        message: '修改成功！'
      })
      ElMessage({
        type: 'error',
        message: '密码已修改，请重新登陆！'
      })
      //修改密码后登出
      request({
        url:'/sys/user/logout',
        method:'get',
        headers: {
          'token': token
        }
      }).then(req=>{
        if (200 == req.data.errorCode){
          sessionStorage.clear()
          router.push("/")
        }
      })
    }else {
      ElMessage({
        type: 'error',
        message: '修改失败！'
      })
    }
  })
  }
  //清空表单数据
  Object.assign(loginForm)
}
//修改密码取消按钮
const cancleFormBtn=()=>{
  // 清空表单数据
  loginFormRef.value.resetFields()
}

// 表单引用
const loginFormRef = ref()
// 表单的数据模型
const loginForm = reactive({
  password : '',
  password2:''
})
// 表单的校验规则
const loginRules = reactive({
  password: [
    { required: true, message: '必须填写密码', trigger: 'blur' },
    /*{ min: 6, message: '账号长度至少6位', trigger: 'blur' },*/
    { pattern : /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$/ ,
      message: '密码必须是数字和字母相结合，长度至少6位！',
      trigger: 'blur' },
  ]
})
//退出按钮
const cancleBtn=()=>{
  // 从SessionStorage取出数据
  let userstr = sessionStorage.getItem('username')
  const token = JSON.parse(userstr).token
  request({
    url:'/sys/user/logout',
    method:'get',
    headers: {
      'token': token
    }
  }).then(req=>{
    if (200 == req.data.errorCode){
      sessionStorage.clear()
      router.push("/")
    }
  })
}

</script>
<style scoped>
.up-row {
  height: 130px;
  line-height: 130px;
  background-image: url("@/assets/imgs/bg.png");
  background-size: cover; /* 使图片平铺满整个浏览器（从宽和高的最大需求方面来满足，会使某些部分无法显示在区域中） */
  color: black;
  font-size: 20px;
  font-weight: bold;
}
/*去掉头像图标，鼠标移上去后的黑色边框*/
:deep(:focus-visible) {
  outline: none;
}
.firstfont{
  font-size: 35px;
  letter-spacing: 10px;
  opacity: 1;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>